﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;

namespace OkTool.Http
{
    /// <summary>
    /// Cookie帮助类
    /// </summary>
    public static class CookieHelper
    {
        /// <summary>
        /// 获取简化COOKIE 删除 setCookie中的 expires=|max-ag=|path=|domain=|HttpOnly
        /// </summary>
        /// <param name="cookies"></param>
        /// <returns></returns>
        public static string GetSmallCookie(IEnumerable<string> cookies)
        {
            string[] strs;
            StringBuilder sb = new StringBuilder(128);
            HashSet<string> hash = new HashSet<string>();
            foreach (var item in cookies)
            {
                strs = item.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var sub in strs)
                {
                    if (!Regex.IsMatch(sub, "expires=|max-ag=|path=|domain=|HttpOnly", RegexOptions.IgnoreCase)) hash.Add(sub.Trim());
                }

            }
            return string.Join("; ", hash);
        }
        public static string GetSmallCookie(string strcookie)
        {
            if (string.IsNullOrWhiteSpace(strcookie))
            {
                return string.Empty;
            }
            List<string> cookielist = new List<string>();
            //将Cookie字符串以,;分开，生成一个字符数组，并删除里面的空项
            string[] list = strcookie.ToString().Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string item in list)
            {
                string itemcookie = item.ToLower().Trim().Replace("\r\n", string.Empty).Replace("\n", string.Empty);
                //排除空字符串
                if (string.IsNullOrWhiteSpace(itemcookie)) continue;
                //排除不存在=号的Cookie项
                if (!itemcookie.Contains("=")) continue;
                //排除path项
                if (itemcookie.Contains("path=")) continue;
                //排除expires项
                if (itemcookie.Contains("expires=")) continue;
                //排除domain项
                if (itemcookie.Contains("domain=")) continue;
                //排除重复项
                if (cookielist.Contains(item)) continue;

                //对接Cookie基本的Key和Value串
                cookielist.Add(string.Format("{0}", item));
            }
            return string.Join("; ", cookielist);
        }
        /// <summary>
        /// 更新cookie
        /// </summary>
        /// <param name="oldCookies"></param>
        /// <param name="newCookies"></param>

        /// <returns></returns>
        public static string UpdateCookie(string oldCookies, string newCookies)
        {
            StringBuilder sb = new StringBuilder();
            Dictionary<string, string> dicCookie = new Dictionary<string, string>();

            if (!string.IsNullOrEmpty(oldCookies))
            {
                foreach (string cookie in oldCookies.Replace(',', ';').Split(new string[] { ";" }, StringSplitOptions.None))
                {
                    if (!string.IsNullOrEmpty(cookie) && cookie.IndexOf('=') > 0)
                    {
                        string key = cookie.Split('=')[0].Trim();
                        string value = cookie.Substring(key.Length + 1).Trim();
                        if (value.ToLower() != "deleted")
                        {
                            if (dicCookie.ContainsKey(key))
                            {
                                dicCookie[key] = cookie.Trim();
                            }
                            else
                            {
                                dicCookie.Add(key, cookie.Trim());
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(newCookies))
            {
                foreach (string cookie in newCookies.Replace(',', ';').Split(new string[] { ";" }, StringSplitOptions.None))
                {
                    if (!string.IsNullOrEmpty(cookie) && cookie.IndexOf('=') > 0)
                    {
                        string key = cookie.Split('=')[0].Trim();
                        string value = cookie.Substring(key.Length + 1).Trim();
                        if (value.ToLower() != "deleted")
                        {
                            if (dicCookie.ContainsKey(key))
                            {
                                dicCookie[key] = cookie.Trim();
                            }
                            else
                            {
                                dicCookie.Add(key, cookie.Trim());
                            }
                        }
                    }
                }
            }
            int i = 0;
            foreach (var item in dicCookie)
            {
                i++;
                if (i < dicCookie.Count)
                {
                    sb.Append(item.Value + "; ");
                }
                else
                {
                    sb.Append(item.Value);
                }
            }

            return sb.ToString();
        }



        /// <summary>
        /// 查询是否有删除指定CookieName值
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="cook_name"></param>
        /// <returns></returns>
        public static bool HasCookie(string cookie, string cook_name)
        {
            if (string.IsNullOrWhiteSpace(cookie)) return false;
            string[] list_New = cookie.ToString().Split(';');

            foreach (string item in list_New)
            {
                //排除重复项
                string[] tmp = item.Trim().Split('=');

                if (tmp[0] == cook_name)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 删除指定CookieName
        /// </summary>
        /// <param name="cook_name"></param>
        /// <returns></returns>
        public static string CookieDelete(string cookie, string cook_name)
        {
            if (string.IsNullOrWhiteSpace(cookie)) return "";

            string[] list_New = cookie.ToString().Split(';');

            string new_cookie = cookie;

            foreach (string item in list_New)
            {
                //排除重复项
                string[] tmp = item.Trim().Split('=');
                if (tmp.Length == 2)
                {
                    if (tmp[0].Equals(cook_name))
                    {
                        new_cookie = new_cookie.Replace(item + ';', "");
                    }

                }
            }
            return new_cookie;
        }

        /// <summary>
        /// 获取指定CookieName值
        /// </summary>
        /// <param name="cook_name"></param>
        /// <returns></returns>
        public static string GetCookValue(string cookie, string cook_name)
        {
            if (string.IsNullOrWhiteSpace(cookie)) return "";

            string[] list_New = cookie.ToString().Split(';');

            string new_cookie = cookie;

            foreach (string item in list_New)
            {
                //排除重复项
                string[] tmp = item.Trim().Split('=');
                if (tmp.Length == 2)
                {
                    if (tmp[0].Equals(cook_name))
                    {
                        return tmp[1];
                    }
                }
            }

            return "";
        }
    }
}
